<template>
  <div class="minesweeper-container">
    <div class="game-header">
      <h1>扫雷</h1>
      <div class="game-controls">
        <div class="difficulty-selector">
          <button 
            v-for="level in difficultyLevels" 
            :key="level.name"
            @click="setDifficulty(level)"
            :class="{ active: currentDifficulty.name === level.name }"
            class="difficulty-btn"
          >
            {{ level.label }}
          </button>
        </div>
        <div class="game-stats">
          <div class="stat">
            <span class="stat-icon">💣</span>
            <span class="stat-value">{{ minesLeft }}</span>
          </div>
          <button @click="resetGame" class="reset-button">
            <span v-if="gameStatus === 'playing'">😊</span>
            <span v-else-if="gameStatus === 'won'">😎</span>
            <span v-else-if="gameStatus === 'lost'">😵</span>
          </button>
          <div class="stat">
            <span class="stat-icon">⏱️</span>
            <span class="stat-value">{{ formatTime(timer) }}</span>
          </div>
        </div>
      </div>
    </div>

    <div class="game-board-container">
      <div 
        class="game-board" 
        :style="{ 
          gridTemplateColumns: `repeat(${currentDifficulty.cols}, 1fr)`,
          gridTemplateRows: `repeat(${currentDifficulty.rows}, 1fr)`
        }"
      >
        <div 
          v-for="(cell, index) in board" 
          :key="index"
          class="cell"
          :class="getCellClass(cell)"
          @click="revealCell(cell)"
          @contextmenu.prevent="flagCell(cell)"
        >
          <template v-if="cell.isRevealed && !cell.isMine">
            <span v-if="cell.adjacentMines > 0" :class="`mines-${cell.adjacentMines}`">
              {{ cell.adjacentMines }}
            </span>
          </template>
          <template v-else-if="cell.isFlagged">
            <span class="flag">🚩</span>
          </template>
          <template v-else-if="cell.isRevealed && cell.isMine">
            <span class="mine">💣</span>
          </template>
        </div>
      </div>
    </div>

    <div class="game-instructions">
      <h3>游戏说明</h3>
      <p>扫雷是一款经典的单人益智游戏，目标是找出所有非地雷的格子，同时避免触发地雷。</p>
      <ul>
        <li><strong>左键点击</strong>: 揭开格子</li>
        <li><strong>右键点击</strong>: 标记地雷</li>
        <li><strong>数字</strong>: 表示周围8个格子中的地雷数量</li>
        <li><strong>难度选择</strong>: 初级(9x9，10个地雷)、中级(16x16，40个地雷)、高级(16x30，99个地雷)</li>
      </ul>
      <p>游戏技巧：</p>
      <ul>
        <li>从角落或边缘开始点击，这些位置周围的地雷数量通常较少</li>
        <li>利用数字推理，标记确定的地雷位置</li>
        <li>当你确定某个格子周围的所有地雷都已标记，可以快速点击该数字格子来揭开周围未标记的格子</li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';

// 难度级别
const difficultyLevels = [
  { name: 'beginner', label: '初级', rows: 9, cols: 9, mines: 10 },
  { name: 'intermediate', label: '中级', rows: 16, cols: 16, mines: 40 },
  { name: 'expert', label: '高级', rows: 16, cols: 30, mines: 99 }
];

// 游戏状态
const currentDifficulty = ref(difficultyLevels[0]);
const board = ref([]);
const gameStatus = ref('playing'); // 'playing', 'won', 'lost'
const timer = ref(0);
const timerInterval = ref(null);
const minesLeft = ref(currentDifficulty.value.mines);

// 设置难度
const setDifficulty = (difficulty) => {
  currentDifficulty.value = difficulty;
  resetGame();
};

// 重置游戏
const resetGame = () => {
  // 停止计时器
  if (timerInterval.value) {
    clearInterval(timerInterval.value);
    timerInterval.value = null;
  }
  
  // 重置游戏状态
  gameStatus.value = 'playing';
  timer.value = 0;
  minesLeft.value = currentDifficulty.value.mines;
  
  // 初始化游戏板
  initBoard();
};

// 初始化游戏板
const initBoard = () => {
  const { rows, cols, mines } = currentDifficulty.value;
  const totalCells = rows * cols;
  
  // 创建空白游戏板
  const newBoard = [];
  for (let i = 0; i < totalCells; i++) {
    const row = Math.floor(i / cols);
    const col = i % cols;
    
    newBoard.push({
      row,
      col,
      isMine: false,
      isRevealed: false,
      isFlagged: false,
      adjacentMines: 0
    });
  }
  
  // 随机放置地雷
  let minesPlaced = 0;
  while (minesPlaced < mines) {
    const randomIndex = Math.floor(Math.random() * totalCells);
    if (!newBoard[randomIndex].isMine) {
      newBoard[randomIndex].isMine = true;
      minesPlaced++;
    }
  }
  
  // 计算每个格子周围的地雷数量
  for (let i = 0; i < totalCells; i++) {
    const cell = newBoard[i];
    if (!cell.isMine) {
      cell.adjacentMines = countAdjacentMines(newBoard, cell.row, cell.col);
    }
  }
  
  board.value = newBoard;
};

// 计算周围地雷数量
const countAdjacentMines = (board, row, col) => {
  const { cols } = currentDifficulty.value;
  let count = 0;
  
  // 检查周围8个方向
  for (let r = -1; r <= 1; r++) {
    for (let c = -1; c <= 1; c++) {
      if (r === 0 && c === 0) continue; // 跳过自身
      
      const newRow = row + r;
      const newCol = col + c;
      const index = newRow * cols + newCol;
      
      // 检查边界
      if (
        newRow >= 0 && 
        newRow < currentDifficulty.value.rows && 
        newCol >= 0 && 
        newCol < cols &&
        board[index].isMine
      ) {
        count++;
      }
    }
  }
  
  return count;
};

// 揭开格子
const revealCell = (cell) => {
  // 如果游戏已结束或格子已被揭开或已标记，则不做任何操作
  if (
    gameStatus.value !== 'playing' || 
    cell.isRevealed || 
    cell.isFlagged
  ) {
    return;
  }
  
  // 第一次点击时开始计时
  if (!timerInterval.value) {
    startTimer();
  }
  
  // 揭开格子
  cell.isRevealed = true;
  
  // 如果点到地雷，游戏结束
  if (cell.isMine) {
    gameOver(false);
    return;
  }
  
  // 如果格子周围没有地雷，自动揭开周围的格子
  if (cell.adjacentMines === 0) {
    revealAdjacentCells(cell);
  }
  
  // 检查是否获胜
  checkWinCondition();
};

// 标记地雷
const flagCell = (cell) => {
  // 如果游戏已结束或格子已被揭开，则不做任何操作
  if (gameStatus.value !== 'playing' || cell.isRevealed) {
    return;
  }
  
  // 第一次操作时开始计时
  if (!timerInterval.value) {
    startTimer();
  }
  
  // 切换标记状态
  cell.isFlagged = !cell.isFlagged;
  
  // 更新剩余地雷数量
  minesLeft.value += cell.isFlagged ? -1 : 1;
};

// 揭开周围的格子
const revealAdjacentCells = (cell) => {
  const { rows, cols } = currentDifficulty.value;
  
  // 检查周围8个方向
  for (let r = -1; r <= 1; r++) {
    for (let c = -1; c <= 1; c++) {
      if (r === 0 && c === 0) continue; // 跳过自身
      
      const newRow = cell.row + r;
      const newCol = cell.col + c;
      
      // 检查边界
      if (
        newRow >= 0 && 
        newRow < rows && 
        newCol >= 0 && 
        newCol < cols
      ) {
        const index = newRow * cols + newCol;
        const adjacentCell = board.value[index];
        
        // 如果相邻格子未被揭开且未被标记，则揭开它
        if (!adjacentCell.isRevealed && !adjacentCell.isFlagged) {
          revealCell(adjacentCell);
        }
      }
    }
  }
};

// 检查是否获胜
const checkWinCondition = () => {
  // 如果所有非地雷格子都被揭开，则获胜
  const allNonMinesRevealed = board.value.every(cell => 
    cell.isRevealed || cell.isMine
  );
  
  if (allNonMinesRevealed) {
    gameOver(true);
  }
};

// 游戏结束
const gameOver = (isWin) => {
  gameStatus.value = isWin ? 'won' : 'lost';
  
  // 停止计时器
  if (timerInterval.value) {
    clearInterval(timerInterval.value);
    timerInterval.value = null;
  }
  
  // 如果失败，揭开所有地雷
  if (!isWin) {
    board.value.forEach(cell => {
      if (cell.isMine) {
        cell.isRevealed = true;
      }
    });
  }
};

// 开始计时器
const startTimer = () => {
  timerInterval.value = setInterval(() => {
    timer.value++;
  }, 1000);
};

// 格式化时间
const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
};

// 获取格子的CSS类
const getCellClass = (cell) => {
  return {
    'revealed': cell.isRevealed,
    'mine': cell.isRevealed && cell.isMine,
    'flagged': cell.isFlagged,
    'exploded': cell.isRevealed && cell.isMine && gameStatus.value === 'lost'
  };
};

// 组件挂载时初始化游戏
onMounted(() => {
  initBoard();
});

// 组件卸载时清除计时器
onUnmounted(() => {
  if (timerInterval.value) {
    clearInterval(timerInterval.value);
  }
});
</script>

<style scoped>
.minesweeper-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.game-header {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.game-header h1 {
  margin: 0;
  color: #333;
  font-size: 28px;
  text-align: center;
}

.game-controls {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.difficulty-selector {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.difficulty-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  background-color: #e2e8f0;
  color: #475569;
  cursor: pointer;
  transition: all 0.2s;
}

.difficulty-btn:hover {
  background-color: #cbd5e1;
}

.difficulty-btn.active {
  background-color: #3b82f6;
  color: white;
}

.game-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f8fafc;
  padding: 10px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: bold;
}

.stat-icon {
  font-size: 24px;
}

.reset-button {
  width: 40px;
  height: 40px;
  border: none;
  border-radius: 50%;
  background-color: #f1f5f9;
  font-size: 24px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  transition: all 0.2s;
}

.reset-button:hover {
  background-color: #e2e8f0;
}

.game-board-container {
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: auto;
}

.game-board {
  display: grid;
  gap: 1px;
  background-color: #94a3b8;
  padding: 2px;
  border-radius: 4px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.cell {
  width: 30px;
  height: 30px;
  background-color: #cbd5e1;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  cursor: pointer;
  user-select: none;
  transition: all 0.1s;
}

.cell:hover {
  background-color: #bfdbfe;
}

.cell.revealed {
  background-color: #f8fafc;
}

.cell.mine {
  background-color: #fee2e2;
}

.cell.exploded {
  background-color: #ef4444;
}

.cell.flagged {
  background-color: #cbd5e1;
}

.mines-1 { color: #3b82f6; }
.mines-2 { color: #16a34a; }
.mines-3 { color: #ef4444; }
.mines-4 { color: #6366f1; }
.mines-5 { color: #b91c1c; }
.mines-6 { color: #0891b2; }
.mines-7 { color: #4b5563; }
.mines-8 { color: #1e293b; }

.game-instructions {
  background-color: #f8fafc;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.game-instructions h3 {
  margin-top: 0;
  color: #333;
}

.game-instructions ul {
  padding-left: 20px;
}

.game-instructions li {
  margin-bottom: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .cell {
    width: 25px;
    height: 25px;
    font-size: 14px;
  }
  
  .game-stats {
    padding: 8px 12px;
  }
  
  .stat {
    font-size: 16px;
  }
  
  .stat-icon {
    font-size: 20px;
  }
  
  .reset-button {
    width: 36px;
    height: 36px;
    font-size: 20px;
  }
}

@media (max-width: 480px) {
  .cell {
    width: 20px;
    height: 20px;
    font-size: 12px;
  }
  
  .difficulty-btn {
    padding: 6px 12px;
    font-size: 14px;
  }
}

/* 暗色主题 */
@media (prefers-color-scheme: dark) {
  .minesweeper-container {
    color: #e2e8f0;
  }
  
  .game-header h1 {
    color: #e2e8f0;
  }
  
  .difficulty-btn {
    background-color: #334155;
    color: #cbd5e1;
  }
  
  .difficulty-btn:hover {
    background-color: #475569;
  }
  
  .difficulty-btn.active {
    background-color: #2563eb;
  }
  
  .game-stats {
    background-color: #1e293b;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }
  
  .reset-button {
    background-color: #334155;
  }
  
  .reset-button:hover {
    background-color: #475569;
  }
  
  .game-board {
    background-color: #475569;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.3);
  }
  
  .cell {
    background-color: #64748b;
  }
  
  .cell:hover {
    background-color: #475569;
  }
  
  .cell.revealed {
    background-color: #1e293b;
  }
  
  .cell.mine {
    background-color: #7f1d1d;
  }
  
  .cell.exploded {
    background-color: #b91c1c;
  }
  
  .cell.flagged {
    background-color: #64748b;
  }
  
  .game-instructions {
    background-color: #1e293b;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }
  
  .game-instructions h3 {
    color: #e2e8f0;
  }
  
  .mines-1 { color: #60a5fa; }
  .mines-2 { color: #4ade80; }
  .mines-3 { color: #f87171; }
  .mines-4 { color: #a5b4fc; }
  .mines-5 { color: #fca5a5; }
  .mines-6 { color: #67e8f9; }
  .mines-7 { color: #9ca3af; }
  .mines-8 { color: #cbd5e1; }
}
</style> 